package br.com.Orange.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import br.com.Orange.hibernate.HibernateUtil;

public class HibernateGenericDAO <ID extends Serializable, Dado >{
	
	private Session session;
	private final Class<Dado> persistentClass;
		
	public HibernateGenericDAO(Class<Dado> persistentClass) {
		this.persistentClass = persistentClass;
	}

	public void save(Dado dado){
		session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(dado);
		tx.commit();
		session.close();
	}
	
	@SuppressWarnings("unchecked")
	public Dado findByID(ID id){
		session = HibernateUtil.getSession();
		Dado dado = (Dado) session.get(persistentClass, id);
		session.close();
		return dado;
	}
	
	public void update(Dado dado) {
		session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.update(dado);
		tx.commit();
		session.close();
	}
	
	public void delete(ID id) {
		Dado dado = findByID(id);
		session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.delete(dado);
		tx.commit();
		session.close();
	}
	
	public boolean exist(ID id){
		if (findByID(id) == null){
			return false;
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public List<Dado> list(){
		session = HibernateUtil.getSession();
		List<Dado> list = session.createCriteria(persistentClass).list();
		session.close();
		return list;
	}	
	
	@SuppressWarnings("unchecked")
	public List<Dado> listByRestriction(String coluna, String query){
		session = HibernateUtil.getSession();
		Criteria c = session.createCriteria(persistentClass);
		c.add(Restrictions.ilike(coluna.trim(), "%"+query.trim()+"%"));
		return c.list();
	}
}
